<template>
    <div ref="tableBox" class="ColumnTable">
        <el-table
            ref="ColumnTable"
            v-loading="loading"
            :border="border"
            :cell-class-name="cellClassName"
            :data="data"
            :default-sort="defaultSort"
            :expand-row-keys="expandRowKeys"
            :height="height"
            :highlight-current-row="highlightCurrentRow"
            :highlight-selection-row="highlightSelectionRow"
            :lazy="lazy"
            :load="load"
            :max-height="maxHeight"
            :row-class-name="rowClassName"
            :row-key="rowKey"
            :row-style="rowStyle"
            :show-summary="showSummary"
            :size="size"
            :span-method="spanMethod"
            :stripe="stripe"
            :summary-method="summaryMethod"
            :tableId="tableId"
            :tree-props="treeProps"
            @select="(selection, row) => $emit('select', selection, row)"
            @select-all="(selection) => $emit('select-all', selection)"
            @selection-change="(selection) => $emit('selection-change', selection)"
            @current-change="(currentRow, oldCurrentRow) => $emit('current-change', currentRow, oldCurrentRow)"
            @row-dblclick="(row, column, event) => $emit('row-dblclick', row, column, event)"
            @row-click="(row, column, event) => $emit('row-click', row, column, event)"
            @expand-change="(row, column, event) => $emit('expand-change', row, column, event)"
            @cell-dblclick="(row, column, cell, event) => $emit('cell-dblclick', row, column, cell, event)"
            @cell-click="(row, column, cell, event) => $emit('cell-click', row, column, cell, event)"
        >
            <el-table-column v-if="showCheckBox" :selectable="selectable" align="center" type="selection" width="60" />
            <el-table-column v-if="showExpand" type="expand" width="60">
                <template #default="props">
                    <slot :props="props.row" name="expand"></slot>
                </template>
            </el-table-column>
            <el-table-column v-if="showIndex" :fixed="indexFixed" :width="indexWidth" align="center" class-name="show__index" label="序号" type="index"></el-table-column>
            <template v-for="(item, index) in columns">
                <el-table-column
                    v-if="item.columnShow && item.children && Array.isArray(item.children)"
                    :key="index"
                    :align="item.align"
                    :fixed="item.fixed"
                    :label="item.title"
                    :label-class-name="item.labelClassName"
                    :min-width="item.minWidth"
                    :prop="item.key"
                    :show-overflow-tooltip="item.showOverflowTooltip || false"
                    :sortable="item.sortable || false"
                    :width="item.width"
                >
                    <el-table-column
                        v-for="(child, index) in item.children"
                        :key="index"
                        :align="child.align"
                        :fixed="child.fixed"
                        :label="child.title"
                        :label-class-name="item.labelClassName"
                        :min-width="item.minWidth"
                        :prop="child.key"
                        :show-overflow-tooltip="child.showOverflowTooltip || false"
                        :sortable="child.sortable || false"
                        :width="child.width"
                    >
                        <template #default="{ row, column, rowIndex }">
                            <slot :column="column" :name="child ? child.key : ''" :row="row" :rowIndex="rowIndex">
                                <span v-if="row[child.key] === null || typeof row[child.key] === undefined"></span>
                                <span v-else-if="item.type && item.type == 'price'">{{row[item.key]? row[item.key].toFixed(4):'0.00' }}</span>
                                <span v-else>{{ row[child.key] }}</span>
                            </slot>
                        </template>
                    </el-table-column>
                    <template v-slot:header #header="scope">
                        <span v-if="item.isFilter">
                            <el-dropdown @command="(command) => handleCommand(command, item.key, index)">
                                <span>
                                    {{ item.title }}
                                    <el-tooltip class="item" content="筛选" effect="dark" placement="top-start">
                                        <img v-if="item.isActive" height="12px" src="./filtersH.png" width="12px" />
                                        <img v-else height="12px" src="./filters.png" width="12px" />
                                    </el-tooltip>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item :tabindex="-1" command="">全部</el-dropdown-item>
                                    <el-dropdown-item
                                        v-for="(val, i) in item.filters"
                                        :key="val.value"
                                        :class="{'is-active': val.isActive}"
                                        :command="val.value"
                                        :tabindex="i"
                                    >
                                        {{ val.label }}
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </span>
                        <span v-else-if="item.isShowHelpIcon" style="display: inline-flex; align-items: center;">
                            {{ item.title }}
                            <el-tooltip class="item" effect="light" placement="top">
                                <div slot="content" v-html="item.helpText"></div>
                                <i class="el-icon-question" style="width: 14px; height: 14px; color: #909399; margin-left: 2px"></i>
                            </el-tooltip>
                        </span>
                        <span v-else>{{ item.title }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    v-if="item.columnShow && !item.children"
                    :key="index"
                    :align="item.align"
                    :fixed="item.fixed"
                    :label="item.title"
                    :label-class-name="item.labelClassName"
                    :min-width="item.minWidth"
                    :prop="item.key"
                    :show-overflow-tooltip="item.showOverflowTooltip || false"
                    :sortable="item.sortable || false"
                    :width="item.width"
                >
                    <template #default="{ row, column, rowIndex }">
                        <slot :column="column" :name="item.key" :row="row" :rowIndex="rowIndex">
                            <span v-if="row[item.key] === null || typeof row[item.key] === undefined"></span>
                            <span v-else-if="item.type && item.type == 'price'">{{ row[item.key]?row[item.key].toFixed(4):'0.00' }}</span>
                            <span v-else-if="row[item.key]==='null'"></span>
                            <span v-else>{{ row[item.key] }}</span>
                        </slot>
                    </template>
                    <template v-slot:header #header="scope">
                        <span v-if="item.isFilter">
                            <el-dropdown @command="(command) => handleCommand(command, item.key, index)">
                                <span>
                                    {{ item.title }}
                                    <el-tooltip class="item" content="筛选" effect="dark" placement="top-start">
                                        <img v-if="item.isActive" height="12px" src="./filtersH.png" width="12px" />
                                        <img v-else height="12px" src="./filters.png" width="12px" />
                                    </el-tooltip>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item :tabindex="-1" command="">全部</el-dropdown-item>
                                    <el-dropdown-item
                                        v-for="(val, i) in item.filters"
                                        :key="val.value"
                                        :class="{'is-active': val.isActive}"
                                        :command="val.value"
                                        :tabindex="i"
                                    >
                                        {{ val.label }}
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </span>
                        <span v-else-if="item.isShowHelpIcon" style="display: inline-flex; align-items: center;">
                            {{ item.title }}
                            <el-tooltip class="item" effect="light" placement="top">
                                <div slot="content" v-html="item.helpText"></div>
                                <i class="el-icon-question" style="width: 14px; height: 14px; color: #909399; margin-left: 2px"></i>
                            </el-tooltip>
                        </span>
                        <span v-else>{{ item.title }}</span>
                    </template>
                </el-table-column>
            </template>
        </el-table>
    </div>
</template>

<script>
export default {
    name: 'ColumnTable',
    // components: { Template },
    props: {
        border: {
            type: Boolean,
            default: () => {
                return true;
            }
        },
        cellClassName: {
            type: Function,
            default: () => {
                return () => {};
            }
        },
        columns: {
            type: Array,
            default: () => {
                return [];
            }
        },
        data: {
            type: Array,
            default: () => {
                return [];
            }
        },
        defaultSort: {
            type: Object,
            default: () => {
                return {};
            }
        },
        expandRowKeys: {
            type: Array
        },
        height: {
            type: [Number, String]
        },
        highlightCurrentRow: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        highlightSelectionRow: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        indexFixed: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        indexWidth: {
            type: [Number, String],
            default: () => {
                return 60;
            }
        },
        lazy: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        load: {
            type: Function,
            default: () => {
                return () => {};
            }
        },
        loading: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        maxHeight: {
            type: [Number, String],
            default: () => {
                return null;
            }
        },
        rowClassName: {
            type: Function,
            default: () => {
                return () => {};
            }
        },
        rowKey: {
            type: String,
            default: () => {
                return '';
            }
        },
        rowStyle: {
            type: Function,
            default: () => {
                return () => {};
            }
        },
        selectable: {
            type: Function,
            default: () => {
                return () => {};
            }
        },
        showCheckBox: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        showExpand: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        showIndex: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        showSummary: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        size: {
            type: String,
            default: () => {
                return '';
            }
        },
        spanMethod: {
            type: Function,
            default: () => {
                return () => {};
            }
        },
        stripe: {
            type: Boolean,
            default: () => {
                return true;
            }
        },
        tableId: {
            type: String,
            default: () => {
                return '';
            }
        },
        treeProps: {
            type: Object,
            default: () => {
                return {};
            }
        },
    },
    methods: {
        // 取消全选
        clearSelection() {
            this.$refs.ColumnTable.clearSelection();
        },
        /**
         *  筛选的行
         * @param command
         * @param key
         * @param index
         */
        handleCommand(command, key, index) {
            let value = command;

            // 如果command不为空
            if (command !== '' && command != null && command.length !== 0) {
                // 如果不允许多选，重置所有isActive并且关闭isActive状态
                if (!this.columns[index].multiple) {
                    this.columns[index].isActive = false;
                    this.columns[index].filters.forEach((item) => {
                        item.isActive = false;
                    });
                }
                // 多选时切换isActive状态
                let i = this.columns[index].filters.findIndex((item) => item.value === command);
                if (i > -1) {
                    this.$set(this.columns[index].filters[i], 'isActive', !this.columns[index].filters[i].isActive);
                }
                this.columns[index].isActive = this.columns[index].filters.some((item) => item.isActive);
            } else {
                // 重置isActive并关闭isActive状态
                this.columns[index].filters.forEach((item) => {
                    item.isActive = false;
                });
                this.columns[index].isActive = false;
            }

            // 如果是多选，获取所有isActive为true的value组成的数组
            if (this.columns[index].multiple) {
                value = this.columns[index].filters.filter((item) => item.isActive).map((item) => item.value);
            } else {
                // 如果不允许多选，直接返回当前选中的value
                value = command;
            }

            this.$emit('filter-click', value, key);
        },
        /**
         * 选中当前行
         * @param row
         */
        setCurrentRow(row) {
            this.$refs.ColumnTable.setCurrentRow(row);
        },
        /**
         *   设置筛选的行
         * @param command
         * @param key
         */
        setFilterActive(command, key) {
            const columnIndex = this.columns.findIndex(item => item.key === key);
            if (columnIndex === -1) return;

            const column = this.columns[columnIndex];

            // Reset filters if command is empty
            if (!command || command.length === 0) {
                column.filters = column.filters.map(({ label, value }) => ({ label, value, isActive: false }));
                column.isActive = false;
                return;
            }

            // Update filter states
            column.filters.forEach(filter => {
                if (column.multiple) {
                    // For multiple selection, check if value is in command array
                    filter.isActive = Array.isArray(command) && command.includes(filter.value);
                } else {
                    // For single selection, check if value matches command
                    filter.isActive = filter.value === command;
                }
            });

            // Update column active state based on if any filters are active
            column.isActive = column.filters.some(filter => filter.isActive);
        },

        //
        summaryMethod(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                // 列名声明为isShowSummary时才显示合计
                if (column.labelClassName && column.labelClassName.includes('isShowSummary')) {
                    const values = data.map((item) => {
                        return Number(item[column.property]) || 0;
                    });
                    if (!values.every((value) => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            let value = Number(curr);
                            prev = !isNaN(Number(prev)) ? Number(prev) : 0;
                            if (!isNaN(value)) {
                                return column.labelClassName && column.labelClassName.includes('price')?Number((prev + curr).toFixed(4)):Number((prev + curr).toFixed(2));
                            } else {
                                if (!isNaN(Number(prev))) {
                                    return Number(prev);
                                }
                                return 0;
                            }
                        }, 0);
                        if (column.labelClassName && column.labelClassName.includes('price')) sums[index] = sums[index].toFixed(4); // 保留4位小数
                    } else {
                        sums[index] = '';
                    }
                } else {
                    sums[index] = '';
                }
            });
            return sums;
        },
        /**
         * 全选
         */
        toggleAllSelection() {
            this.$refs.ColumnTable.toggleAllSelection();
        },
        /**
         * 切换展开状态
         */
        toggleRowExpansion(row) {
            this.$refs.ColumnTable.toggleRowExpansion(row);
        },
        // 多选选中或取消
        toggleRowSelection(row, flag) {
            this.$refs.ColumnTable.toggleRowSelection(row, flag);
        }
    }
};
</script>
<style scoped>
.ColumnTable {
    padding-bottom: 4px;
}
.department-table-style.ColumnTable {
    padding: 0;
}
.el-dropdown img {
    margin: -2px 0;
}
.is-active {
    background-color: #e8f4ff;
    color: #46a6ff;
}
.el-table .el-dropdown span {
    font-size: 13px;
    color: #515a6e;
}
</style>
